package com.gmrz.uaf.crypto;

import com.gmrz.util.Convert;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

/**
 * 生成uaf.default.external.encryption.key参数
 * Created by yihui on 2017/7/6.
 */
public class AESKeyGenerator {


    private static final String transformation = "AES/GCM/NoPadding";

    public static void main(String args[]){
        try {

            byte [] serverDataKey = generate();
            byte[] wrappedKey = encrypt(serverDataKey);
            System.out.println("将此值填入数据库t_uas_config表中的config_name中uaf.default.external.encryption.key字段对应的config_value中："+Base64.encodeBase64URLSafeString(wrappedKey));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] encrypt(byte[] data) throws GeneralSecurityException {
        Security.addProvider(new BouncyCastleProvider());
        byte[] iv = null;
        IvParameterSpec ivSpec = null;
        Cipher cipher = Cipher.getInstance(transformation,"BC");

        iv = generateIV(cipher.getBlockSize());
        ivSpec = new IvParameterSpec(iv);
        cipher.init(1, getKey(), ivSpec);
        return ArrayUtils.addAll(iv, cipher.doFinal(data));
    }

    public static byte[] generateIV(int blockSize) {
        byte[] ivBytes = new byte[blockSize];
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivBytes);
        return ivBytes;
    }
    /**
     *
     * @return
     * @throws GeneralSecurityException
     */
    public static byte[] generate() throws GeneralSecurityException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey key = keyGenerator.generateKey();
        return key.getEncoded();
    }
    /**
     * 随机生成秘钥
     */
    public static SecretKey getKey()throws NoSuchAlgorithmException{
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256
        SecretKey sk = kg.generateKey();
        byte[] b = sk.getEncoded();
        System.out.println("将此值填入com.gmrz.uaf.crypto.internal.handlers包下ServerDataKeyParser类中的wrapKey参数："+Convert.toHex(b));
        return new SecretKeySpec(b, "AES");
    }


}
